#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "load.h"
#include "elf.h"
#include "endian.h"


int main(int argc, char* argv[]){
	
	if(argc != 3){
		printf ("\n\nErreur d'utilisation du programme !\n\nSyntaxe : >./etape3 nom_fich.o num_section|nom_section\n\n");
		return 0;
	}

	if(!estELF(argv[1])){
		printf ("\n\nErreur d'utilisation du programme !\n\nSyntaxe : >./etape3 nom_fich.o num_section|nom_section\n\n");
		return 0;
	}

	char nom[50];
	char c;
	int i=0,j=0,decode[16];
	FILE* f;
	f = fopen(argv[1],"r");

	if(f!=NULL){
		Elf32_Off offset = -1;
		Elf32_Word size;
		Elf32_Word name;

		Elf32_Ehdr header = load_header(f);
		Elf32_Shdr* sheader = load_section_headers(f);

		while(i<header.e_shnum){
			if(atoi(argv[2])==i){ 
				offset = sheader[i].sh_offset; 
				size = sheader[i].sh_size ;
				name = sheader[i].sh_name ;
			}


			fseek (f ,sheader[header.e_shstrndx].sh_offset + sheader[i].sh_name, SEEK_SET);
			c = (char)fgetc(f);
			while (c != '\0') {
			        nom[j] = c;
			        c = (char)fgetc(f);
			        j++;
			}
			nom[j] = c;
			j=0;

			int egal=1;

			if(strlen(argv[2])<=50){
				while(egal && j<strlen(argv[2])){
					if(argv[2][j]!=nom[j]){
						egal = 0;
					}
					j++;
				}
				if(egal){
					offset = sheader[i].sh_offset; 
					size = sheader[i].sh_size ;
					name = sheader[i].sh_name ;
				}		
			}

			j=0;
			i++;
		}

		if(offset == -1){
			printf("\n\nErreur : aucune réponse pour l'argument : %s.\n\n",argv[2]);
			return 0;
		}


		if(size==0){
			printf("\n\nSection '%s' has no data to dump.\n\n",getnom(f,name));
			return 0;
		}

		printf("\nHex dump of section '%s':",getnom(f,name));

		int b;
		unsigned char car=0;
		fseek (f ,offset, SEEK_SET);
		for(i=0;i<(size);i++){
			if(i%16==0 && i!=0){
				printf(" ");
				for(b=0;b<16;b++){
					printf("%c",decode[b]);
				}
			}
			if(i%4==0 && i!=0){
				printf(" ");
			}
			if(i%16==0){
				printf("\n\t0x%08x ",i);
			}

			fread(&car ,1 ,1 ,f );

			if(car>=32 && car <=126)
				decode[i%16]=car;
			else
				decode[i%16]=46;

			printf("%02x",car);
		}

		i=size%16;
		if(i!=0){
			while(i<16){
				printf("  ");
				if(i%4==0 && i!=0){
					printf(" ");
				}
				i++;
			}
		}
		printf(" ");
		if(size%16==0){
			for(b=0;b<16;b++){
				printf("%c",decode[b]);
			}
		} else {		
			for(b=0;b<(size%16);b++){
				printf("%c",decode[b]);
			}
		}

		printf("\n\n");
		fclose(f);
	}

	return 0;
}

